package cn.tedu.blogproject.controller;


import cn.tedu.blogproject.common.response.JsonResult;
import cn.tedu.blogproject.common.response.StatusCode;
import cn.tedu.blogproject.mapper.WeiboMapper;
import cn.tedu.blogproject.pojo.dto.WeiboDTO;
import cn.tedu.blogproject.pojo.dto.WeiboIndexVO;
import cn.tedu.blogproject.pojo.entity.Weibo;
import cn.tedu.blogproject.pojo.vo.UserVO;
import cn.tedu.blogproject.pojo.vo.WeiboDetailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerInterceptor;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Api(tags = "微博管理模块")
@Slf4j
@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {

    @Autowired
    private WeiboMapper weiboMapper;

    @ApiOperation(value = "发布微博方法")
    @PostMapping("insert")
    public JsonResult insertWeiBo(@RequestBody WeiboDTO weiboDTO , @ApiIgnore HttpSession session){
        log.debug("WeiboDTOz: " + weiboDTO);
        Weibo weibo = new Weibo();
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        BeanUtils.copyProperties(weiboDTO,weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.insertWeibo(weibo);
        return JsonResult.ok();
    }

    @ApiOperation(value = "微博首页列表方法")
    @GetMapping("selectIndex")
    public JsonResult selectIndex(){
        List<WeiboIndexVO> IndexList = weiboMapper.selectAll();
        for (WeiboIndexVO weiboIndexVO : IndexList){
            log.debug("微博： "+weiboIndexVO);
        }
        return new JsonResult(StatusCode.OPERATION_SUCCESS,IndexList);
    }

    @ApiOperation(value = "微博详情页方法")
    @GetMapping("selectById")
    @ApiImplicitParams(value = {
        @ApiImplicitParam(name = "id",value = "微博ID",required = true,example = "201"),
        @ApiImplicitParam(name = "username",value = "用户名",required = true,example = "徐晴")
    })
    public JsonResult selectById(Long id,String username){
        if(id < 0){
            throw new IllegalArgumentException("参数不可小于0");
        }
        List<WeiboDetailVO> weiboDetailList =  weiboMapper.selectByIdAndUsername(id,username);
        return new JsonResult(StatusCode.OPERATION_SUCCESS,weiboDetailList);
    }
}
